<?php

/**
 * 
 * @author zhouming
 *
 */
class Product_model extends MY_Model {
	public function __construct() {
		parent::__construct ();
	}
	/**
	 * 修改商品数据
	 * 
	 * @param int $id
	 *        	商品ID
	 * @param array $paramData
	 *        	商品所需数据
	 */
	public function update($id, $paramData) {
		$postData = array ();
		$nowDataTime = ITime::getDateTime ();
		$goodsAttrData = array ();
		$goodsUpdateData = array ();
		foreach ( $paramData as $key => $val ) {
			$postData [$key] = $val;
			
			// 数据过滤分组
			if (strpos ( $key, 'attr_base' ) !== false) {
				$goodsAttrData ['attr_base'] [] = explode ( ',', IFilter::act ( $val ) );
			} else if (strpos ( $key, 'attr_sku' ) !== false) {
				foreach ( $val as $attrSku ) {
					$goodsAttrData ['attr_sku'] [] = explode ( ',', IFilter::act ( $attrSku ) );
				}
			} else if (strpos ( $key, 'attr_search' ) !== false) {
				foreach ( $val as $attrSku ) {
					$goodsAttrData ['attr_search'] [] = explode ( ',', IFilter::act ( $attrSku ) );
				}
			} else if ($key == 'content') {
// 				$goodsUpdateData ['content'] = IFilter::addSlash ( $val );
				$goodsUpdateData ['content'] = $val;
			} else if ($key [0] != '_') {
				$goodsUpdateData [$key] = IFilter::act ( $val, 'text' );
			}
		}
		$default = isset ($postData['is_default']) ? $postData['is_default'] : 0; //默认产品
		
		$goodsUpdateData ['goods_no'] = isset ( $postData ['_goods_no'] ) ? $postData ['_goods_no'][$default] : '';
		$goodsUpdateData ['store_nums'] = array_sum ( $postData ['_store_nums'] );
		$goodsUpdateData ['market_price'] = isset ( $postData ['_market_price'] ) ? $postData ['_market_price'][$default] : 0;
		$goodsUpdateData ['sell_price'] = isset ( $postData ['_sell_price'] ) ? $postData ['_sell_price'][$default]  : 0;
		$goodsUpdateData ['cost_price'] = isset ( $postData ['_cost_price'] ) ? $postData ['_cost_price'][$default]  : 0;
		$goodsUpdateData ['cash_back'] = isset ( $postData ['_cash_back'] ) ? $postData ['_cash_back'][$default]  : 0;
		$goodsUpdateData ['proportion'] = isset ( $postData ['_proportion'] ) ? $postData ['_proportion'][$default] : 0;
		$goodsUpdateData ['member_proportion'] = isset ( $postData ['_member_proportion'] ) ? $postData ['_member_proportion'][$default] : 0;
		$goodsUpdateData ['area_proportion'] = isset ( $postData ['_area_proportion'] ) ? $postData ['_area_proportion'][$default] : 0;
		$goodsUpdateData ['weight'] = isset ( $postData ['_weight'] ) ? $postData ['_weight'][$default]  : 0;
		$goodsUpdateData ['goods_img'] = isset ( $postData ['_goods_img'] ) ? $postData ['_goods_img'][$default]  : '';

		// 处理商品
		$category = explode ( ',', $goodsUpdateData ['categroy_id'] );
		if (strpos ( $goodsUpdateData ['goods_no'], '-' ) !== false) {
			$goodsUpdateData ['goods_no'] = array_shift ( explode ( '-', $goodsUpdateData ['goods_no'] ) );
		}
		$productBaseData = array (
				'first_cat_id' => $category [0],
				'second_cat_id' => $category [1],
				'product_code' => $goodsUpdateData ['goods_no'],
				'product_name' => $goodsUpdateData ['title'],
				'product_image' => $goodsUpdateData ['img'],
				'brand_id' => $goodsUpdateData ['brand'] ? $goodsUpdateData ['brand'] : 0,
				'shop_id' => $goodsUpdateData ['shop'],
				'market_price' => $goodsUpdateData ['market_price'],
				'per_price' => $goodsUpdateData ['sell_price'],
				'member_price' => $goodsUpdateData ['sell_price'],
				'cost_price' => $goodsUpdateData ['cost_price'],
				'cash_back' => $goodsUpdateData ['cash_back'],
				'shelf' => $goodsUpdateData ['shelves'],
                'stock' => $goodsUpdateData ['stock'],
				'status' => 2,
				'f_order' => $goodsUpdateData ['sort'],
				'product_info' => $goodsUpdateData ['content'],
				'precise_unit' => $goodsUpdateData ['unit'],
				'seo_keywords' => $goodsUpdateData ['keywords'],
				'seo_description' => $goodsUpdateData ['description'],
				'inventory' => $goodsUpdateData ['store_nums']
		);
		if ($id) {
			$this->db->where ( 'id', $id )->update ('dwf_product', $productBaseData);
		} else {
			$this->db->insert ( 'dwf_product', $productBaseData );
			$id = $this->db->insert_id ();
		}

		// 处理商品属性
		$this->db->delete ( 'dwf_product_attribute_key_value', array (
				'product_id' => $id 
		) ); // 删除现有属性
		$productAttr = array ();
		if (isset ( $goodsAttrData ['attr_base'] ) && ! empty ( $goodsAttrData ['attr_base'] )) {
			foreach ( $goodsAttrData ['attr_base'] as $value ) {
				$productAttr [] = array (
						'product_id' => $id,
						'attribute_id' => $value [0],
						'attribute_value_id' => $value [1],
						'is_sku' => 0 
				);
			}
		}
		if (isset ( $goodsAttrData ['attr_sku'] ) && ! empty ( $goodsAttrData ['attr_sku'] )) {
			foreach ( $goodsAttrData ['attr_sku'] as $value ) {
				$productAttr [] = array (
						'product_id' => $id,
						'attribute_id' => $value [0],
						'attribute_value_id' => $value [1],
						'is_sku' => 1 
				);
			}
		}
		if (isset ( $goodsAttrData ['attr_search'] ) && ! empty ( $goodsAttrData ['attr_search'] )) {
			foreach ( $goodsAttrData ['attr_search'] as $value ) {
				$productAttr [] = array (
						'product_id' => $id,
						'attribute_id' => $value [0],
						'attribute_value_id' => $value [1],
						'is_sku' => 0 
				);
			}
		}
		if (! empty ( $productAttr )) {
			$this->db->insert_batch ( 'dwf_product_attribute_key_value', $productAttr );
		}
		
// 		// 处理商品规格
// 		$this->db->delete ( 'dwf_product_goods', array (
// 				'product_id' => $id 
// 		) ); // 删除现有规格
		$productsData = array ();
		if (isset ( $postData ['_spec_array'] )) {
			$productIdArray = array ();
			
			// 创建货品信息
			foreach ( $postData ['_goods_no'] as $key => $rs ) {
				$sku_key = array ();
				$sku_array = $postData ['_spec_array'] [$key];
				foreach ( $sku_array as $value ) {
					$sku_temp = JSON::decode ( $value );
					$sku_key [$sku_temp ['id']] = $sku_temp ['value'];
				}
				ksort ( $sku_key );
				$is_default = 0;
				if(isset($postData['is_default']) && $postData['is_default'] == $key){
					$is_default = 1;
				}elseif(!isset($postData['is_default']) && $key == 0){
					$is_default = 1;
				}
// 				print_r($postData);exit;
				$productsData [] = array (
						'product_id' => $id,
						'goods_no' => $postData ['_goods_no'] [$key],
						'store_nums' => $postData ['_store_nums'] [$key],
						'market_price' => $postData ['_market_price'] [$key],
						'sell_price' => $postData ['_sell_price'] [$key],
						'cost_price' => $postData ['_cost_price'] [$key],
						'area_proportion' => $postData ['_area_proportion'] [$key],
						'member_proportion' => $postData ['_member_proportion'] [$key],
						'proportion' => $postData ['_proportion'] [$key],
						'cash_back' => $postData ['_cash_back'] [$key],
						'create_time' => date ( 'Y-m-d H:i:s' ),
						'sku_key' => JSON::encode ( $sku_key ),
						'is_default' => $is_default,
                        'goods_img' => $postData ['_goods_img'] [$key]
				);
			}
		} else {
			$goods_no = $postData ['_goods_no'] [0];
			if(strpos($postData ['_goods_no'] [0], '-') === false){
				$goods_no = $postData ['_goods_no'] [0] . '-1';
			}
			$productsData [] = array (
					'product_id' => $id,
					'goods_no' => $goods_no,
					'store_nums' => $postData ['_store_nums'] [0],
					'market_price' => $postData ['_market_price'] [0],
					'sell_price' => $postData ['_sell_price'] [0],
					'cost_price' => $postData ['_cost_price'] [0],
					'area_proportion' => $postData ['_area_proportion'] [0],
					'member_proportion' => $postData ['_member_proportion'] [0],
					'proportion' => $postData ['_proportion'] [0],
					'cash_back' => $postData ['_cash_back'] [0],
					'create_time' => date ( 'Y-m-d H:i:s' ),
					'sku_key' => NULL ,
					'is_default'=>1,
                    'goods_img' => $postData ['_goods_img'] [0]
			);
		}
		$this->handleProductGoodsData($id, $productsData); //goodsData处理
		
		// 处理商品分类
		
		$this->db->delete ( 'dwf_product_category', array (
				'product_id' => $id 
		) );
		$product_category = array ();
		foreach ( $category as $value ) {
			$product_category [] = array (
					'product_id' => $id,
					'category_id' => $value 
			);
		}
		if (! empty ( $product_category )) {
			$this->db->insert_batch ( 'dwf_product_category', $product_category );
		}
		// 处理商品图片
		$this->db->delete ( 'dwf_product_image', array (
				'product_id' => $id 
		) );
		$postData ['_imgList'] = trim ( $postData ['_imgList'], ',' );
		$product_image = array ();
		if (isset ( $postData ['_imgList'] ) && $postData ['_imgList']) {
			$postData ['_imgList'] = explode ( ",", $postData ['_imgList'] );
			$postData ['_imgList'] = array_filter ( $postData ['_imgList'] );
			if ($postData ['_imgList']) {
				foreach ( $postData ['_imgList'] as $key => $val ) {
					$product_image [] = array (
							'product_id' => $id,
							'image' => $val 
					);
				}
			}
		}
		if (! empty ( $product_image )) {
			$this->db->insert_batch ( 'dwf_product_image', $product_image );
		}

		return $id;
	}
	/**
	 * 处理产品规格数据
	 * @param unknown $product_id
	 * @param unknown $goodsData
	 */
	private function handleProductGoodsData($product_id , $goodsData){
		$goodsDataOld = $this->db->select('id,sku_key')
								->from('dwf_product_goods')
								->where('product_id',$product_id)
								->get()
								->result_array();
		
		$goodsDataInsert= array();
		$goodsDataUpdate = array();
		$goodsDataDelete = $goodsDataOld;
		foreach($goodsData as $value){
			$flag = 0;
			foreach($goodsDataOld as $k=> $v){
				if($v['sku_key'] == $value['sku_key']){
					$goodsDataUpdate[] = $value;
					unset($goodsDataDelete[$k]);
					$flag = 1;
					break;
				}
			}
			if($flag == 0){
				$goodsDataInsert[] = $value;
			}			
		}
		foreach($goodsDataDelete as $value){
			$this->db->delete('dwf_product_goods', array('id' => $value['id']));
		}
		foreach($goodsDataUpdate as $value){
			$this->db->update('dwf_product_goods', $value, array('product_id' => $value['product_id'],'sku_key'=>$value['sku_key']));
		}
		if (! empty ( $goodsDataInsert )) {
			$this->db->insert_batch ( 'dwf_product_goods', $goodsDataInsert );
		}
		return true;
	}
	/**
	 * 获取商品基础数据
	 * 
	 * @param unknown $id        	
	 */
	public function getProductBaseData($id) {
		$productBaseData = array ();
		if ($id > 0) {
			$productBaseData = $this->db->select ( '`id`,`product_code`,`product_name`,`product_image`,`brand_id`,`shop_id`,`shelf`,`stock`,`product_info`,`f_order`,`seo_keywords`,`seo_description`,`precise_unit`,`f_order`' )->from ( 'dwf_product' )->where ( 'id', $id )->get ()->row_array ();
		}
		return $productBaseData;
	}
	/**
	 * 获取产关联属性
	 * 
	 * @param unknown $productId        	
	 * @return unknown
	 */
	public function getProductAttrbute($productId) {
		$productAttrbute = $this->db->where ( 'product_id', $productId )->get ( 'dwf_product_attribute_key_value' )->result_array ();
		return $productAttrbute;
	}
	/**
	 * 获取货品信息
	 * @param unknown $productId
	 * @return unknown
	 */
	public function getProductGoodsData($productId) {
// 		$productGoodsData = $this->db->where ( 'product_id', $productId )->get ( 'dwf_product_goods' )->result_array ();
		$productGoodsData = $this->db->select('a.*,b.product_name')
									->from('dwf_product_goods as a')
									->join('dwf_product as b' ,'a.product_id = b.id' , 'left')
									->where('a.product_id' , $productId)
                                    //->where('a.product_id', $productId)
									->get()
									->result_array();
		return $productGoodsData;
	}
	/**
	 * 获取商品图片
	 * @param unknown $productId
	 * @return unknown
	 */
	public function getProductImages($productId) {
		$productImages = $this->db->where ( 'product_id', $productId )
								->order_by('id ASC')
								->get ( 'dwf_product_image' )
								->result_array ();
		return $productImages;
	}
	/**
	 * 获取产品分类
	 * @param unknown $productId
	 */
	public function getProductCategory($productId){
		$category = $this->db->select('b.*')
							->from('dwf_product_category as a')
							->join('dwf_category as b' ,'a.category_id = b.id','left')
							->where('a.product_id' , $productId)
							->order_by('b.parent_id ASC')
							->get()
							->result_array();
		return $category;
								
	}
	/**
	 * 批量获取产品
	 * @param unknown $param
	 */
	public function getProductList($param) {
		$productList = array();
		if(isset($param['where']) && !empty($param['where'])){$this->db->where($param['where']);}
		if(isset($param['like']) && !empty($param['like'])){$this->db->like($param['like']);}
		if(isset($param['where_in']) && !empty($param['where_in'])){
			foreach($param['where_in'] as $key=>$value){
				if(!empty($value)){
					$this->db->where_in($key , $value);
				}
			}
		}
		$productNum =  $this->db->count_all_results('`dwf_product`',FALSE);
		if(isset($param['fields'])){
			$fields = $param['fields'];
		}else{
			$fields = '`id`,`product_code`,`product_name`,`product_image`,`brand_id`,`precise_unit`,`calculate_method`,`measure_unit`,`shop_id`,`per_price`,`member_price`,`detail`,`member_proportion`,`area_proportion`,`proportion`,`product_info`,`remark`,`inventory`,`shelf`,`stock`,`cash_back`,`count`,`f_order`,`seckill`';
		}
		$this->db->select($fields);
		if(isset($param['limit']) && !empty($param['limit'])){
			if(is_array($param['limit'])){
				$this->db->limit($param['limit'][1] , $param['limit'][0]);
			}else{
				$this->db->limit($param['limit']);
			}
		}
		if(isset($param['order_by']) && $param['order_by'] != '')$this->db->order_by($param['order_by']);
		$products = $this->db->get()->result_array();
		$products = $this->getProductExtendData($products);
		$productList = array('productNum'=>$productNum , 'products'=>$products);
		return $productList;
	}
	/**
	 * 获取产品附加数据
	 * @param unknown $products
	 * @return unknown
	 */
	private function getProductExtendData($products){
		$productsIds = array();
		$productsNew = array();
		foreach($products as $value){
			$productsIds[] = $value['id'];
			$productsNew[$value['id']] = $value;
		}
		/**获取分类信息*/
		if(!empty($productsIds)){
			$categoryData = $this->db->select('a.product_id , a.category_id , b.category_name')
									->from('dwf_product_category as a ')
									->join('dwf_category as b' ,'a.category_id = b.id' , 'left')
									->where_in('a.product_id' ,$productsIds )
									->get()
									->result_array();

			foreach($categoryData as $value){
				$productsNew[$value['product_id']]['category'][] = $value;
			}
		}
		return $productsNew;
	}
	
	/**
	 * 查询分类关联的产品id
	 * @param unknown $categoryId
	 * @return unknown[]
	 */
	public function getProductIdForCategory($categoryId){
		$productIds = array();
		if(is_array($categoryId)){
		    $this->db->where_in('category_id', $categoryId);
        }else{
		    $this->db->where('category_id', $categoryId);
        }
        $this->db->order_by('category_id asc');
		$productId = $this->db->select('product_id')->get('dwf_product_category')->result_array();
		foreach($productId as $value){
			$productIds[] = $value['product_id'];
		}
		
		return $productIds;
	}
	/**
	 * 商品编号模糊查询商品id
	 * @param unknown $goodsNo
	 * @return unknown[]
	 */
	public function getProductIdForGoodsNo($goodsNo){
		$productIds = array();
		$productId = $this->db->select('product_id')->like('goods_no',$goodsNo)->get('dwf_product_goods')->result_array();
		foreach($productId as $value){
			$productIds[] = $value['product_id'];
		}
		return $productIds;
	}

    /**
     * 更新产品的备货状态
     */
    public function updateProductStock($productId, $stock){
        $data = array('stock' => $stock);
        if(is_array($productId)){
            $this->db->where_in('id',$productId);
        }else{
            $this->db->where('id' , $productId);
        }
        $this->db->update('dwf_product',$data);
        return true;
    }

	/**
	 * 更新产品上下架
	 * @param unknown $productId
	 * @param unknown $shelf
	 */
	public function updateProductShelf($productId , $shelf){
		$data = array('shelf'=>$shelf);
		if(is_array($productId)){
			$this->db->where_in('id',$productId);
		}else{
			$this->db->where('id' , $productId);
		}
		$this->db->update('dwf_product',$data);
		return true;
	}

    /**
     * 更新SKU上下架
     * @param unknown $goodsId
     * @param unknown $shelf
     */
    public function updateGoodsShelf($goodsId , $shelf){
        $data = array('shelf'=>$shelf);
        if(is_array($goodsId)){
            $this->db->where_in('id', $goodsId);
        }else{
            $this->db->where('id', $goodsId);
        }
        $this->db->update('dwf_product_goods', $data);
        return true;
    }

    /**
     * 更新SKU库存
     * @param unknown $goodsId
     * @param unknown $store
     */
    public function updateGoodsStore($goodsId , $store){
        $data = array('store_nums'=>$store);
        if(is_array($goodsId)){
            $this->db->where_in('id', $goodsId);
        }else{
            $this->db->where('id', $goodsId);
        }
        $this->db->update('dwf_product_goods', $data);
        return true;
    }

    /**
     * 更新SKU价格
     * @param unknown $goodsId
     * @param unknown $price
     */
    public function updateGoodsPrice($goodsId , $price){
        $data = array('sell_price'=>$price);
        if(is_array($goodsId)){
            $this->db->where_in('id', $goodsId);
        }else{
            $this->db->where('id', $goodsId);
        }
        $this->db->update('dwf_product_goods', $data);
        return true;
    }
    
    public function updateGoodsVipPrice($goodsId , $price){
        $data = array('vip_price'=>$price);
        $this->db->where('id', $goodsId)->update('dwf_product_goods', $data);
        return true;
    }

    /**
     * 更新SKU计量单位
     * @param unknown $goodsId
     * @param unknown $precise
     */
    public function updateGoodsPrecise($goodsId , $precise){
        $data = array('precise_unit'=>$precise);
        if(is_array($goodsId)){
            $this->db->where_in('id', $goodsId);
        }else{
            $this->db->where('id', $goodsId);
        }
        $this->db->update('dwf_product_goods', $data);
        return true;
    }

	/**
	 * 修改产品排序
	 * @param unknown $productId
	 * @param unknown $sort
	 */
	public function updateProductSort($productId , $sort){
		$data = array('f_order'=>$sort);
		$this->db->where('id' , $productId)->update('dwf_product',$data);
		return true;
	}
	/**
	 * 删除产品
	 * @param unknown $productId
	 */
	public function deleteProduct($productId){
		if(is_array($productId)){
			$this->db->where_in('id',$productId);
		}else{
			$this->db->where('id' , $productId);
		}
		$this->db->delete('dwf_product');
		$this->db->reset_query();
		if(is_array($productId)){
			$this->db->where_in('product_id',$productId);
		}else{
			$this->db->where('product_id' , $productId);
		}
		$this->db->delete('dwf_product_goods');
		return true;
	}
	/**
	 * 更新库存
	 * @param unknown $product_id
	 * @param unknown $total_num
	 * @param unknown $store_array
	 */
	public function updateProductStore($product_id ,$total_num, $store_array){
		$this->db->update_batch('dwf_product_goods', $store_array, 'id');
		$this->db->where('id',$product_id)->update('dwf_product',array('inventory'=>$total_num));
		return true;
	}
	/**
	 * 更新产品价格
	 */
	public function updateProductPrice($product_id , $product_price , $price_array){
		$this->db->update_batch('dwf_product_goods', $price_array, 'id');
		$this->db->where('id',$product_id)->update('dwf_product',$product_price);
		return true;
	}

    /**
     * 获取产品所有SKU属性
     * @param $productId
     * @return array
     */
    public function getProductSku($productId){
        $defaultSku = $this -> getDefaultProductSku($productId);
        $singleSpec = [];//单规格产品
        if(!isset($defaultSku[0][0]['aid'])){
            $singleSpec[$defaultSku[2]][0]['aid'] = $defaultSku[2];
            $singleSpec[$defaultSku[2]][0]['is_default'] = 1;
            $singleSpec[$defaultSku[2]][0]['store_nums'] = $defaultSku[3];
        }
        $defaultSku = $defaultSku[0];
        $defaultSkuKey = [];
        for($i = 0; $i < count($defaultSku); $i++){
            if(isset($defaultSku[$i]['aid'])) {
                $defaultSkuKey[$defaultSku[$i]['aid']] = $defaultSku[$i]['vid'];
            }
        }
        $sku = $this -> db -> select('a.id as aid, a.attribute_name as aname, v.id as vid, v.value_name as vname')
            -> from('dwf_product_attribute_key_value as k')
            -> join('dwf_product_attribute as a', 'k.attribute_id = a.id', 'left')
            -> join('dwf_product_attribute_value as v', 'k.attribute_value_id = v.id', 'left')
            -> where(
                array('k.is_sku' => '1', 'k.product_id' => $productId, 'a.attribute_type' => '3')
            )
            -> order_by('a.id asc, v.id asc')
            -> get()
            -> result_array();
        $skuList = [];
        if(empty($sku)){
            $skuList = $singleSpec;
        }else {
            for ($i = 0; $i < count($sku); $i++) {
                $skuList[$sku[$i]['aid']][$i] = $sku[$i];
                if (in_array($sku[$i]['aid'], array_keys($defaultSkuKey)) && !empty($defaultSkuKey)) {
                    if (in_array($sku[$i]['vid'], $defaultSkuKey)) {
                        $skuList[$sku[$i]['aid']][$i]['is_default'] = 1;
                        $skuList[$sku[$i]['aid']][$i]['store_nums'] = $defaultSku[0]['store_nums'];
                    } else {
                        $skuList[$sku[$i]['aid']][$i]['is_default'] = 0;
                        $skuList[$sku[$i]['aid']][$i]['store_nums'] = 0;
                    }
                } else {
                    $skuList[$sku[$i]['aid']][$i]['is_default'] = 0;
                    $skuList[$sku[$i]['aid']][$i]['store_nums'] = 0;
                }
                $skuList[$sku[$i]['aid']] = array_values($skuList[$sku[$i]['aid']]);
            }
        }
        return array_values($skuList);
    }

    /**
     * 产品默认SKU
     * @param unknown $productId
     */
    public function getDefaultProductSku($productId){
        $defaultSku = [];
        $defaultSkuKeyStr = $this -> db -> select('id,sku_key,sell_price,store_nums')
            -> from('dwf_product_goods')
            -> where(
                array(
                    'product_id' => $productId,
                    'is_default' => '1'
                )
            )
            -> limit(1)
            -> get()
            -> result_array();
        if(empty($defaultSkuKeyStr)){

            $defaultSkuKeyStr = $this -> db -> select('id,sku_key,sell_price,store_nums')
                -> from('dwf_product_goods')
                -> where(
                    array(
                        'product_id' => $productId,
                    )
                )
                -> limit(1)
                -> get()
                -> result_array();
        }
        $skuKey = json_decode($defaultSkuKeyStr[0]['sku_key'], true);

        foreach($skuKey as $k => $v){
            $defaultSkuTmp = $this -> db
                -> select('a.id as aid, a.attribute_name as aname, v.id as vid, v.value_name as vname')
                -> from('dwf_product_attribute as a')
                -> join('dwf_product_attribute_value as v', 'v.attribute_id = a.id' , 'left')
                -> where(
                    array(
                        'a.id' => $k,
                        'v.id' => $v
                    )
                )
                -> get()
                -> result_array();
            $defaultSku[] = $defaultSkuTmp[0];

        }
        $defaultSku[0] = $defaultSku;
        $defaultSku[0][0]['store_nums'] = $defaultSkuKeyStr[0]['store_nums'];
        $defaultSku[1] = $defaultSkuKeyStr[0]['sell_price'];
        $defaultSku[2] = $defaultSkuKeyStr[0]['id'];
        $defaultSku[3] = $defaultSkuKeyStr[0]['store_nums'];
        return $defaultSku;
    }


    /**
     * 获取货品2 用于商品列表中多规格的显示，便于快速修改库存等
     * $isSeckill 获取商品在秒杀状态下信息
     */
    public function getProductGoods($productId, $isSeckill = false) {
        $data = array();
        $productId = IFilter::act($productId, 'int');
        if($productId > 0) {
            $this->load->model('productAttribute_model');
            $seckillData = array();
            //if($isSeckill){
                $this->load->model('seckill_model');
                $seckillData = $this->seckill_model->getSeckillData($productId);
            //}
            $productGoodsData = $this->getProductGoodsData($productId);
            $skuAttrIds = array ();
            foreach ( $productGoodsData as $key => $value ) {
                $temp = JSON::decode ( $value ['sku_key'] );
                foreach ( $temp as $k => $val ) {
                    $skuAttrIds [] = $k;
                }
                //if($isSeckill && !empty($seckillData)){
                if(!empty($seckillData)){
                    foreach($seckillData as $k => $v){
                        if($v['product_id'] == $value['product_id'] && $v['goods_id'] == $value['id']){
                            $productGoodsData[$key]['seckill_detail'] = array(
                                'store_nums' => $v['store_nums'],
                                'store_nums_real' => $v['store_nums_real'],
                                'store' => ($v['store_nums'] + $v['store_nums_real']),
                                'sell_price' => $v['sell_price']
                            );
                        }
                    }
                }
            }
            $skuAttrIds = array_unique ( $skuAttrIds );
            $checkedAttrebute = array ();
            if (! empty ( $skuAttrIds )) {
                $param = array (
                    'where_in' => array (
                        'id' => $skuAttrIds
                    )
                );
                $checkedAttrebute = $this->productAttribute_model->getProductAttribute($param);
                unset ( $checkedAttrebute ['ids'] );
            }
            foreach ( $productGoodsData as $key => $value ) {
                $temp = JSON::decode ( $value ['sku_key'] );
                $spec_array = array ();
                $spec = array ();
                foreach ( $temp as $k => $val ) {
                    foreach ( $checkedAttrebute [$k] ['values'] as $t ) {
                        if ($t ['id'] == $val) {
                            $spec ['value'] = $t['value_name'];
                            break;
                        }
                    }
                    $spec_array [] = $spec;
                }
                $productGoodsData [$key] ['spec_array'] = $spec_array;
            }
            foreach ( $checkedAttrebute as $key => $value ) {
                $checkedAttrebute [$key] ['name'] = $value ['attribute_name'];
                $checkedAttrebute [$key] ['type'] = $value ['attribute_type'];
            }
            $data = $productGoodsData;
        }
        return $data;
    }

    /**
     * 获取所有goods信息 如：库存低于10的商品
     */
    public function getAllProductId($param = array()){
        if(isset($param['where']) && !empty($param['where'])){$this->db->where($param['where']);}
        if(isset($param['where_in']) && !empty($param['where_in'])){
            foreach($param['where_in'] as $key=>$value){
                if(!empty($value)){
                    $this->db->where_in($key , $value);
                }
            }
        }
        $pids = array();
        $productsId = $this->db->select('a.product_id')
            ->from('dwf_product_goods as a')
            ->group_by('product_id')
            ->get()
            ->result_array();
        if(!empty($productsId)){
            foreach($productsId as $key => $value){
                $pids[] = $value['product_id'];
            }
        }
        return $pids;
    }

    /**
     * 设置产品默认SKU
     */
    public function setDefaultSku($pid, $gid){
        $where = array('product_id' => $pid);
        $this->db->update('dwf_product_goods', array('is_default' => '0'), $where);
        $where2 = array('id' => $gid);
        $this->db->update('dwf_product_goods', array('is_default' => '1'), $where2);
        return true;
    }

    /**
     * 产品真实库存入库
     */
    public function setRealStoreNum($gid, $num, $type, $operate, $price){
        $setStr = ($type == 'plus')?'store_nums_real +'. $num: 'store_nums_real -'. $num;
        $this->db->where('id', $gid);
        $this->db->set('store_nums_real', $setStr, false);
        $this->db->update('dwf_product_goods');
        $this->load->model('log/stock_model', 'stock_log');
        $type = ($type == 'plus')?'0':'1';
        $this->stock_log->insertLog($gid, $num, $type, $operate, $price);
        return true;
    }

    /**
     * 获取单品的真实与虚拟库存
     * @param int $gid
     * @return array
     */
    public function getStoreNum($gid = 0){
        $realStore = array();
        if($gid > 0){
            $realStore = $this->db->select('store_nums,store_nums_real')
                               ->from('dwf_product_goods')
                               ->where('id', $gid)
                               ->get()
                               ->result_array();
        }
        return $realStore[0];
    }

    /**
     * 更新单品真实库存
     * @param $gid
     * @param $num
     * @return mixed
     */
    public function updateStoreNum($gid, $store, $storeReal){
        $where = array('id' => $gid);
        $result = $this->db->update('dwf_product_goods', array('store_nums' => $store, 'store_nums_real' => $storeReal), $where);
        return $result;
    }

    /**
     * 根据goodsID获取sku名
     * @param $gid
     * @return array
     */
    public function getGoodsSkuNameByGid($gid){
        $skuInfo = [];
        $goodsSku = $this->db->select('sku_key')
                             ->from('dwf_product_goods')
                             ->where('id', $gid)
                             ->get()
                             ->result_array();
        if(!empty($goodsSku)){
            $skuInfo = $this->getSkuName($goodsSku[0]['sku_key'], ',');
        }
        return $skuInfo;
    }


    /**
     * 获取所选规格属性ID对应sku名
     * @param $skuKey
     * @return array
     */
    public function getSkuName($skuKey, $explodeStr = ''){
        $skuName = '';
        $skuKey = json_decode($skuKey, true);
        foreach($skuKey as $k => $v){
            $defaultSkuTmp = $this -> db -> select('v.id as vid, v.value_name as vname')
                -> from('dwf_product_attribute_value as v')
                -> where(
                    array(
                        'id' => $v
                    )
                )
                -> get()
                -> result_array();
            $explodeStr = $explodeStr == ''?'&nbsp;':$explodeStr;
            $skuName .= $defaultSkuTmp[0]['vname'].$explodeStr;
        }
        return $skuName;
    }

    /*public function getSkuNameByGid($goodsId){
        $skuInfo = [];
        $sql = 'select `sku_key`,`sell_price`,`proportion`,`area_proportion`,`cash_back` from `dwf_product_goods` where id = '.$goodsId;
        $skuList = $this -> queryRow($sql);
        if(!empty($skuList)){
            $skuInfo['sku_name'] = $this -> getSkuName($skuList['sku_key'],',');
            $skuInfo['sell_price'] = $skuList['sell_price'];
            $skuInfo['proportion'] = $skuList['proportion'];
            $skuInfo['area_proportion'] = $skuList['area_proportion'];
            $skuInfo['cash_back'] = $skuList['cash_back'];
        }
        return $skuInfo;
    }*/
}
